#include "llist.h"

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

unsigned int lappend(LList** list, void* data)
{
	LList* m = malloc(sizeof(LList));
	m->data = data;
	m->next = NULL;

	if(*list == NULL)
	{
		*list = m;
		return 0;
	}
	else
	{
		LList* l;
		int i = 0;
		for(l=*list; l->next; l=l->next, ++i);
		l->next = m;
		return i;
	}
}

unsigned int lcount(LList** list)
{
	if(!*list)
		return 0;
	else
	{
		LList* l;
		unsigned int i;
		for(l=*list, i=0; l; l=l->next, i++);
		return i;
	}
}

int lfind(LList** list, void* data)
{
	if(!*list)
		return -1;
	else
	{
		LList* l;
		unsigned int i;
		for(l=*list, i=0; l; l=l->next, i++)
			if(l->data == data)
				return i;
		return -1;
	}
}

int lfindstr(LList** list, char* data)
{
	if(!*list)
		return -1;
	else
	{
		LList* l;
		unsigned int i;
		for(l=*list, i=0; l; l=l->next, i++)
			if(!strcmp((char*)l->data, data))
				return i;
		return -1;
	}
}

void linsert(LList** list, unsigned int i, void* data)
{
	// create new node
	LList *new = NULL;
	lappend(&new, data);

	if(i == 0)
	{
		new->next = *list;
		*list = new;
	}
	else
	{
		// find node minus one
		unsigned int j;
		LList *prev;
		for(j=0, prev=*list; j<(i-1); ++j, prev=prev->next)
			if(!prev->next)
			{
				fprintf(stderr, "List overflow.\n");
				exit(1);
			}
		LList *next = prev->next;
		new->next = next;
		prev->next = new;
	}
}

void lremove(LList** list, void* data)
{
	(void)list;
	(void)data;
	// TODO
	abort();
}

void* ldelete(LList** list, int i)
{
	if(!*list)
	{
		fprintf(stderr, "List overflow.\n");
		exit(1);
	}
	else if(i == 0)
	{
		void *data = (*list)->data;
		LList *m = (*list)->next;
		free(*list);
		*list = m;
		return data;
	}
	else
		abort(); // TODO not implemented
}

void clear(LList** list)
{
	LList* l = *list;

	while(!empty(&l))
		ldelete(&l, 0);

	*list = NULL;
}

#if 0
int main()
{
	char two[] = "two";

	LList *list = NULL;
	lappend(&list, "one");
	//linsert(&list, 0, "mid");

	printf("%d\n", lcount(&list));

	return 0;
}
#endif
